package com.ynny.librarysystemmanager.controller;

import com.ynny.librarysystemmanager.common.R;
import com.ynny.librarysystemmanager.entity.User;
import com.ynny.librarysystemmanager.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    UserService userService;

    public static final String SESSION_KEY = "USER_SESSION";

    @GetMapping
    public R login(){

        return R.fail(440,"请先登录");
    }

    @PostMapping
    public R login(@RequestBody User user , HttpSession session){

        User loginSuccesUser = userService.login(user.getUsername(),user.getPassword());

        if (loginSuccesUser != null){
            session.setAttribute(SESSION_KEY , user.getUsername());
            loginSuccesUser.setPassword("猜猜我的密码！！！");
            return R.ok(loginSuccesUser);
        }else {
            return R.fail(400,"用户名或密码错误");
        }

    }


    //退出登录
    @PostMapping("/out")
    public R logout(HttpSession session){

        //清空session中的信息

        session.removeAttribute(SESSION_KEY);

        return R.ok(null);

    }


}
